package netWork;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class MyUdpEchoServer {

    //网络编程接口套接字
    private DatagramSocket socket = null;

    public MyUdpEchoServer(int port) throws SocketException {
        socket = new DatagramSocket(port);
    }

    //服务器的启动方法
    public void start() throws IOException {
        System.out.println("服务器启动");

        //同样使用循环的方法使服务器持续接受请求
        while(true){
            //读取客户端的请求并解析
            DatagramPacket requestPacket = new DatagramPacket(new byte[4096],4096);
            //同样的还是用 socket 来接收请求
            socket.receive(requestPacket);
            //上述收到的数据是通过二进制来传输的
            String request = new String(requestPacket.getData(),0,requestPacket.getLength());
            //根据请求计算响应
            String response = process(request);
            //把响应传给客户端
            DatagramPacket PacketResponse = new DatagramPacket(response.getBytes(),response.getBytes().length,requestPacket.getSocketAddress());
            socket.send(PacketResponse);
            //打印日志
            System.out.printf("[%s : %d] , req = %s : res = %s\n",requestPacket.getAddress(),requestPacket.getPort(),request,response);
        }
    }
    public String process(String response){
        return response;
    }

    public static void main(String[] args) throws IOException {
        MyUdpEchoServer server = new MyUdpEchoServer(9090);
        server.start();
    }
}
